package com.sun.androidexerciseproject.function.livedata.activity;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;

import com.sun.androidexerciseproject.function.R;
import com.sun.androidexerciseproject.function.livedata.viewmodel.NameViewModel;

public class NameActivity extends AppCompatActivity {
    private NameViewModel model;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_name);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            if (null != model) {
                model.getCurrentName().setValue("fab clicked!");
            }
        });
        initView();
        initData();
    }

    private void initData() {
        model = ViewModelProviders.of(this).get(NameViewModel.class);
        final Observer<String> nameObserver = new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        };
        model.getCurrentName().observe(this, nameObserver);
    }

    private void initView() {
        textView = findViewById(R.id.tv_content);
    }

    @Override
    protected void onPause() {
        super.onPause();
        new Thread() {
            @Override
            public void run() {
                model.getCurrentName().postValue("onPause");
            }
        }.start();
    }

}
